<template>
	<view class="product-detail">
		<CustomNavBar class="navbar">
			<template v-slot:left>
				<view class="back uni-flex uni-align-center uni-justify-center" @click="goBack">
					<uni-icons type="left" size="20"></uni-icons>
				</view>
			</template>
		</CustomNavBar>
		<view class="img-box">
			<uni-swiper-dot class="uni-swiper-dot-box" :info="foundationInfo.baseBannerImgs" :current="currentSwiper"
				mode="dot" :dots-styles="dotsStyles" field="content">
				<swiper class="swiper-box" :autoplay="true" :interval="5000" :duration="500" :current="currentSwiper"
					@change="changeSwiper" circular>
					<swiper-item v-for="(item, index) in foundationInfo.baseBannerImgs" :key="index">
						<view class="swiper-item">
							<image class="product-image" mode="aspectFill" :src="item" />
						</view>
					</swiper-item>
				</swiper>
			</uni-swiper-dot>
		</view>

		<view class="product-info">
			<view class="detail">
				<view class="priceBox uni-flex uni-align-center">
					<view class="price-title">券后价</view>
					<view class="price"><text class="price-symbol">￥</text>{{ filteredPrice.preferentialPrice }}</view>
					<view class="original-price">￥{{ filteredPrice.marketPrice }}</view>
				</view>
				<view class="Coupons uni-flex uni-justify-between">
					<view class="Coupons-box uni-flex uni-align-center">
						<view class="Coupons-item">新用户立减</view>
						<view class="Coupons-item">满100减10</view>
					</view>
					<view class="Coupons-btn" @click='goCoupon(foundationInfo.itemId)'>
						领券<uni-icons type="right" size="16" color="#FF6A47"></uni-icons>
					</view>
				</view>
				<view class="product-title">{{ detailData.itemRemark }}</view>
				<view class="sales uni-flex">
					<view class="sales-title" v-for='(item,index) in itemParamList' :key="index"
						:class="{ 'selected': selectedParamId === item.id }" @click="handleParamSelect(item.id)">
						{{item.specsName}}
					</view>
				</view>

				<view class="safeguard uni-flex uni-align-center">
					<image :src="`${$ImgBaseUrl}lfbz.png`" alt="safeguard-image" class="safeguard-image" />
					<view class="safeguard-title">零负保障</view>
					<view class="safeguard-content">服务超出预定时间，半小时内免费</view>
				</view>
			</view>
		</view>
		<view class="content">
			<view class="demand">
				<view class="title uni-flex">
					<image :src="`${$ImgBaseUrl}detail_label.png`" mode="widthFix" />
					<text>服务内容</text>
					<image :src="`${$ImgBaseUrl}detail_label.png`" mode="widthFix" />
				</view>
				<view class="content-box">
					<!-- 服务内容 -->
					<rich-text :nodes="serviceContentHtml"></rich-text>

					<!-- 服务标准内容展示逻辑：分情况处理 -->
					<template v-if="foundationInfo.stdSevStatus === '0'">
						<!-- 情况1：当 stdLinkStatus 为0时，显示折叠面板 -->
						<template v-if="foundationInfo.stdLinkStatus === '0'">
							<view class="std-content-container" @click="isStdContentExpanded = !isStdContentExpanded">
								<view class="std-content-header uni-flex uni-justify-between uni-align-center">
									<text class="std-title">服务标准内容</text>
									<uni-icons :type="isStdContentExpanded ? 'up' : 'down'" size="24"
										color="#666"></uni-icons>
								</view>
								<view class="std-content-wrapper" v-if="isStdContentExpanded">
									<rich-text :nodes="stdSveContentHtml"></rich-text>
								</view>
							</view>
						</template>

						<!-- 情况2：当 stdLinkStatus 不为0时，直接显示内容 -->
						<template v-else>
							<rich-text :nodes="stdSveContentHtml"></rich-text>
						</template>
					</template>
				</view>
			</view>
		</view>
		<uni-goods-nav :fill="true" :options="options" :buttonGroup="buttonGroup" @click="onClick"
			@buttonClick="buttonClick" class="uni-goods-nav" />
		<SelectSpecificationsPopup ref="popupSelectorRef"></SelectSpecificationsPopup>
	</view>
</template>


<script setup>
	import CustomNavBar from '@/components/custom-navbar/index.vue';
	import SelectSpecificationsPopup from './SelectSpecificationsPopup.vue';
	import {
		useCartStore
	} from '@/store/cart.js';
	const cartStore = useCartStore()
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		getSevItemInfo
	} from '@/api/home.js';
	import {
		PeopleDetailCollect
	} from '@/api/findPeople.js'
	import {
		ref,
		computed,
		watch,
		onMounted,
		reactive
	} from 'vue';


	// 定义响应式数据
	const foundationInfo = ref({});
	const itemParamList = ref([]);
	const detailData = ref('');
	const serviceContentHtml = ref('');
	const stdSveContentHtml = ref('');
	const popupSelectorRef = ref(null);
	const selectedParamId = ref('');
	const currentSwiper = ref(0);
	const options = ref([{
		icon: 'star',
		text: '收藏'
	}, {
		icon: 'cart',
		text: '购物车',
		info: cartStore.count
	}]);
	const buttonGroup = ref([{
		text: '加入购物车',
		backgroundColor: '#FEB310',
		color: '#fff'
	}, {
		text: '立即下单',
		backgroundColor: '#2F80ED',
		color: '#fff'
	}]);
	const dotsStyles = reactive({
		backgroundColor: 'rgba(255, 255, 255, 0.7)',
		color: '#fff',
		selectedBackgroundColor: '#fff',
		selectedBorder: 'none',
		border: 'none'
	});
	const id = ref('');
	const showDialog = ref(false);
	const collectState = ref(null);
	const couponId = ref('')
	// 新增：控制服务标准内容折叠/展开的状态变量（核心修复点）
	const isStdContentExpanded = ref(false); // 默认折叠
	// 监听购物车数量变化
	watch(
		() => cartStore.count,
		(newCount) => {
			options.value[1].info = newCount; // 安全更新响应式属性
		}, {
			immediate: true
		} // 初始化时立即执行一次，确保初始值正确
	);
	onLoad((options) => {
		id.value = options.id;
		if (options.couponId) {
			couponId.value = options.couponId;
			console.log('接收到的优惠券ID:', couponId.value);
			// 可以在这里调用接口，使用优惠券ID获取优惠信息
		}
		fetchAndProcessDetail();
	});
	// 在onMounted中初始化购物车数量
	onMounted(async () => {
		await cartStore.initCartCount(); // 等待接口返回后再更新UI
	});
	// 方法定义
	const goBack = () => {
		uni.navigateBack({
			delta: 1
		});
	};

	const changeSwiper = (e) => {
		currentSwiper.value = e.detail.current;
	};

	const addToCart = () => {
		uni.showToast({
			title: '商品已加入购物车',
			icon: 'none'
		});
	};

	const onClick = async (e) => {
		if (e.index === 0) {
			try {
				const params = {
					collectId: foundationInfo.value.localId,
					collectType: "VIEW_SONIC",
					isCollect: !collectState.value
				};
				const res = await PeopleDetailCollect(params);
				if (res.code === 200) {
					collectState.value = !collectState.value;
					uni.showToast({
						title: collectState.value ? '收藏成功' : '取消收藏成功',
						icon: 'none'
					});
					options.value[0].icon = collectState.value ? 'star-filled' : 'star';
				} else {
					uni.showToast({
						title: res.msg || '操作失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('收藏接口调用失败:', error);
				uni.showToast({
					title: res.msg || '网络异常，操作失败',
					icon: 'none'
				});
			}
		} else if (e.index === 1) {
			uni.navigateTo({
				url: '/pages/shoppingCart/cart'
			});
		}
	};

	const goCoupon = (itemId) => {
		console.log('itemId', itemId);
		uni.navigateTo({
			url: `/pages/viewSonic/ViewCoupon?itemId=${itemId}`
		});
	};

	const handleParamSelect = (id) => {
		selectedParamId.value = id;
	};

	const buttonClick = (e) => {
		console.log('立即下单');
		popupSelectorRef.value.openPopup(detailData.value,couponId.value);
	};

	const filteredPrice = computed(() => {
		if (!detailData.value || !detailData.value.itemPriceList) {
			return {
				preferentialPrice: foundationInfo.value.paramMinPrice || 0,
				marketPrice: foundationInfo.value.paramMaxPrice || 0
			};
		}

		let validItems = detailData.value.itemPriceList.filter(item => {
			const statusMatch = item.status === "0";
			const paramMatch = !selectedParamId.value || item.localParamId === selectedParamId.value;
			return statusMatch && paramMatch;
		});

		if (validItems.length === 0) {
			return {
				preferentialPrice: foundationInfo.value.paramMinPrice || 0,
				marketPrice: foundationInfo.value.paramMaxPrice || 0
			};
		}

		const minPriceItem = validItems.reduce((min, current) => {
			return current.priceAmount < min.priceAmount ? current : min;
		}, validItems[0]);

		return {
			preferentialPrice: minPriceItem.preferentialPrice,
			marketPrice: minPriceItem.priceAmount
		};
	});

	const fetchAndProcessDetail = async () => {
		try {
			const res = await getSevItemInfo(id.value);
			if (res.code === 200) {
				collectState.value = res.isCollect;
				foundationInfo.value = res.serviceItemInfo;
				itemParamList.value = res.itemParamList;
				serviceContentHtml.value = res.serviceItemInfo.baseDesc;
				stdSveContentHtml.value = res.serviceItemInfo.stdSevContent;
				detailData.value = res;

				options.value[0].icon = collectState.value ? 'star-filled' : 'star';
				if (itemParamList.value.length > 0) {
					selectedParamId.value = itemParamList.value[0].id;
				}
			}
		} catch (error) {
			console.error('请求失败:', error);
			throw error;
		}
	};
</script>

<style scoped lang="scss">
	.product-detail {
		padding: 0 0 180rpx;
		position: relative;
		background: #F5F5F5;

		.navbar {
			position: absolute;
		}

		.back {
			width: 44rpx;
			height: 44rpx;
			background: rgba(255, 255, 255, 0.6);
			border-radius: 50%;
		}

		.img-box {
			width: 100%;
			height: 675rpx;
			// overflow: hidden; // 配合aspectFill裁剪超出部分
			position: relative;

			.swiper-box {
				width: 100%;
				height: 675rpx; // 使swiper填满容器
			}

			.swiper-item {
				width: 100%;
				height: 100%; // 使swiper-item填满swiper
			}

			.product-image {
				width: 100%;
				height: 100%;
				object-fit: cover;
				// display: block;
			}
		}

		.product-info {
			padding: 24rpx;

			.detail {
				background: linear-gradient(180deg, #E1EEFF 0%, #FEFFFF 52%, #FFFFFF 100%);
				border-radius: 20rpx;
				padding: 24rpx;

				.price-title {
					font-weight: 400;
					font-size: 20rpx;
					color: #FF6A47;
					margin-right: 8rpx;
				}

				.price {
					font-size: 40rpx;
					font-weight: bold;
					color: #FF6A47;
					margin-right: 15rpx;
				}

				.price-symbol {
					font-size: 24rpx;
					color: #FF6A47;
				}

				.original-price {
					font-size: 22rpx;
					color: #999999;
					text-decoration: line-through;
				}

				.Coupons {
					margin: 18rpx 0 24rpx;

					.Coupons-box {
						.Coupons-item {
							padding: 6rpx 10rpx;
							margin-right: 16rpx;
							background: #FFE1DA;
							border-radius: 6rpx;
							font-size: 24rpx;
							color: #FF6A47;
						}
					}

					.Coupons-btn {
						font-size: 28rpx;
						color: #FF6A47;
					}
				}

				.product-title {
					font-weight: 600;
					font-size: 34rpx;
					color: #333333;
					margin-bottom: 20rpx;
					/* 隐藏超出容器的内容 */
					overflow: hidden;
					/* 设置显示的行数 */
					display: -webkit-box;
					-webkit-line-clamp: 2; /* 控制显示的行数 */
					-webkit-box-orient: vertical; /* 垂直排列 */
					white-space: normal; /* 允许文本换行 */
					/* 不需要设置text-overflow: ellipsis，因为webkit-line-clamp会自动处理省略号 */
				}

				.sales-title {
					padding: 15rpx 10rpx;
					background: #F0F0F0;
					border-radius: 10rpx;
					font-weight: 600;
					font-size: 30rpx;
					color: #666666;
					margin-right: 20rpx;
					cursor: pointer;
					transition: all 0.3s;
					&.selected {
						background: #E6F0FF;
						color: #2F80ED;
						border: 1rpx solid #2F80ED;
					}
				}

				.safeguard {
					margin-top: 25rpx;

					.safeguard-image {
						width: 28rpx;
						height: 32rpx;
						margin-right: 10rpx;
					}

					.safeguard-title {
						font-weight: 400;
						font-size: 24rpx;
						color: #DEB36F;
					}

					.safeguard-content {
						font-weight: 400;
						font-size: 24rpx;
						color: #666666;
						margin-left: 16rpx;
					}
				}
			}
		}

		.content {
			padding: 0 24rpx 0 24rpx;
		}

		.demand {
			background: white;
			border-radius: 20rpx;
			padding: 20rpx;
			margin-bottom: 24rpx;

			.content-box {

				/* 服务标准内容样式 */
				.std-content-container {
					margin-top: 20rpx;
					border: 1px solid #f0f0f0;
					border-radius: 10rpx;
					overflow: hidden;
				}

				.std-content-header {
					padding: 15rpx 20rpx;
					background-color: #f9f9f9;
					cursor: pointer;

					.std-title {
						font-size: 30rpx;
						font-weight: 500;
						color: #333;
					}
				}

				.std-content-wrapper {
					padding: 20rpx;
					background-color: #fff;
					transition: all 0.3s ease;
				}
			}

			.title {
				justify-content: center;
				align-items: center;
				margin-bottom: 6rpx;

				image {
					width: 32rpx;
				}

				text {
					font-weight: 500;
					font-size: 36rpx;
					color: #333333;
					margin: 0 24rpx;
				}
			}
		}

		.uni-goods-nav {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 154rpx;
			background: #ffffff;
			padding: 12rpx 23rpx 0;
		}
	}

	::v-deep .uniui-star-filled {
		color: #2F80ED !important;
		font-size: 38rpx !important;
	}

	::v-deep .uniui-star {
		font-size: 38rpx !important;
	}

	::v-deep .uniui-cart {
		font-size: 40rpx !important;
	}

	::v-deep .uni-tab__cart-box {
		height: 100rpx !important;
	}
</style>